<?php
header('Content-Type: application/json');

// 错误处理
set_error_handler(function($severity, $message, $file, $line) {
    error_log("PHP Error: $message in $file on line $line");
    http_response_code(500);
    echo json_encode(['error' => 'Internal Server Error']);
    exit;
});

// 加载配置
$config = @include 'config.php';
if (!$config || empty($config['chatkey'])) {
    http_response_code(500);
    echo json_encode(['error' => '服务器配置错误']);
    exit;
}

// 获取请求数据
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['question'])) {
    http_response_code(400);
    echo json_encode(['error' => '无效请求']);
    exit;
}

// 构建消息历史
$messages = [];

// 检查 history 是否存在且为数组
if (isset($data['history']) && is_array($data['history'])) {
    foreach ($data['history'] as $msg) {
        if (empty($msg['content'])) {
            continue; // 跳过无效消息
        }
        // 确保每个消息对象包含必要字段
        if (is_array($msg) && isset($msg['role'], $msg['content'])) {
            $messages[] = [
                'role' => $msg['role'],
                'content' => $msg['content']
            ];
        }
    }
}

$messages[] = ['role' => 'user', 'content' => $data['question']];

// 调用DeepSeek API
$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => 'https://api.deepseek.com/v1/chat/completions',
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $config['chatkey'],
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'model' => 'deepseek-chat',
        'messages' => $messages,
        'temperature' => 0.7
    ]),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30
]);

$response = curl_exec($ch);

if (!$response) {
    $curlError = curl_error($ch);
    echo json_encode(array("cURL 请求失败: " . $curlError));
    exit;
    http_response_code(500);
    echo json_encode(['error' => 'API请求失败: ' . curl_error($ch)]);
    exit;
}

$result = json_decode($response, true);
if (isset($result['error'])) {
    http_response_code(500);
    echo json_encode(['error' => $result['error']['message']]);
    exit;
}

echo json_encode([
    'answer' => $result['choices'][0]['message']['content']
]);

curl_close($ch);
?>